package com.sl.au.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.sl.au.entity.*;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sl.au.repository.TaskRepository;
import com.sl.au.service.ErrorStatusService;
import com.sl.au.service.IndexService;
import com.sl.au.service.OptionService;
import com.sl.au.service.PartsAttributesService;
import com.sl.au.service.PartsTypeService;
import com.sl.au.service.PartsWarnService;
import com.sl.au.service.SectionService;
import com.sl.au.service.WarnStatusService;
import com.sl.utils.DataConverter;

import org.springframework.util.StringUtils;

@Service("IndexService")
@Transactional
public class IndexServiceImpl extends BaseServiceImpl implements IndexService {
	@Autowired
	TaskRepository taskRepository;
	@Autowired
	SectionService sectionService;
	
	@Autowired
	PartsTypeService partsTypeService;
	@Resource
	JdbcTemplate jdbcTemplate;
	@Autowired
	PartsAttributesService partsAttributesService;
	@Autowired
	PartsWarnService partsWarnService;
	
	@Autowired
	OptionService optionService;
	@Autowired
	WarnStatusService warnStatusService;
	@Autowired
	ErrorStatusService errorStatusService;
	
	
	@Override
	public TaskRepository getRepository() {

		return this.taskRepository;
	}


	@Override
	public List<Task> getMyTask(int start, int length, String userId, String roleId) {
		Page<Task> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		pages = taskRepository.getMyTask(userId, roleId, pageable);
		return pages.getContent();
	}


	@Override
	public Map<String, Object> newAddCount(Map<String, String> condition) {
		Map<String, Object> count=new HashMap<String, Object>();	
		long contractCount=0;
		long customerCount=0;
		long chanceCount=0;		
		contractCount=this.getNewContract(condition);
		chanceCount=this.getNewChance(condition);
		customerCount=this.getNewCustomer(condition);
		count.put("contractCount", contractCount);
		count.put("cusCount", customerCount);
		count.put("chanceCount", chanceCount);
		return count;
	}



	@Override
	public void getAafterSale() {
		// TODO Auto-generated method stub
		
	}


	@Override
	public long getNewChance(Map<String, String> condition) {
		// TODO Auto-generated method stub
		return 0;
	}


	@Override
	public long getNewContract(Map<String, String> condition) {
		// TODO Auto-generated method stub
		return 0;
	}


	@Override
	public long getNewCustomer(Map<String, String> condition) {
		// TODO Auto-generated method stub
		return 0;
	}


	@Override
	public void getParts(String id, Map<String, Object> map) {
		map.put("count", 0);
		if(StringUtils.hasText(id)) {
			String SQL = "select * from t_partscommon where  id ='" + id +"'";
			List<Map<String,Object>> lst = new ArrayList<Map<String,Object>>();
			lst = jdbcTemplate.queryForList(SQL);
			if(lst.size() > 0) {
				Map<String,Object> result = lst.get(0);
				String parts_Type = (String) result.get("parts_Type");
				PartsType partsType = partsTypeService.getRepository().findPartsTypeByPartType(parts_Type);
				/* 获取基本数据信息 */
				//部件名
				String parts_name = (String) result.get("parts_name");
				//设备类型名称
				String partsname = partsType.getParts_name();
				//企业名称
				String company_name = (String) result.get("company_name");
				//警告类型代码
				String warnStatus = (String) result.get("warnStatus");
				//警告类型
				String warnStatusName = this.getWarnStatus(parts_Type, warnStatus);
				//警告说明
				String warnExp = (String) result.get("warnExp");
				
				//故障类型代码
				String errorStatus = (String) result.get("errorStatus");
				//故障类型
				String errorStatusName = this.getErrorStatus(errorStatus);
				//故障说明
				String errorExp = (String) result.get("errorExp");
				
				//数据时间
				String sendDate = result.get("sendDate") != null ? String.valueOf(result.get("sendDate")) : "";
				//起始时间
				String startDate = result.get("startDate") != null ? String.valueOf(result.get("startDate")) : sendDate;
				//结束时间
				String endDate =  result.get("endDate") != null ? String.valueOf(result.get("endDate")) : "";
				//持续时间
				String keepTime = result.get("keepTime") != null ? String.valueOf(result.get("keepTime")) : "0";
				
				//格式转换
				String reg = "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})";
				sendDate = sendDate.replaceAll(reg, "$1-$2-$3 $4:$5:$6");
				startDate = startDate.replaceAll(reg, "$1-$2-$3 $4:$5:$6");
				endDate = endDate.equals("") ? "" : endDate.replaceAll(reg, "$1-$2-$3 $4:$5:$6");
				
				map.put("parts_name", parts_name);
				map.put("partsname", partsname);
				map.put("company_name", company_name);
				map.put("warnStatusName", warnStatusName);
				map.put("warnExp", warnExp);
				map.put("errorStatusName", errorStatusName);
				map.put("errorExp", errorExp);
				map.put("sendDate", sendDate);
				map.put("startDate", startDate);
				map.put("endDate", endDate);
				map.put("keepTime", keepTime);
				
				
				List<PartsAttributes> partsAttributess = null;
//				partsAttributess = partsAttributesService.getPage(0, Integer.MAX_VALUE, partsType.getId(), "");
				partsAttributess = partsAttributesService.getRepository().findAllPartsAtrributesByTypeidOrderColumn(partsType.getId());
				map.put("count", partsAttributess.size());
				if(partsAttributess.size() > 0) {
					for(int i=0;i<partsAttributess.size();i++) {
						PartsAttributes partsAttributes = partsAttributess.get(i);
						String attributes_name = partsAttributes.getAttributes();
						String column_name= partsAttributes.getColumn_name();
						map.put("name"+i, attributes_name);
						map.put("value"+i, result.get(column_name));
						Double value = result.get(column_name) == null? null: Double.valueOf(String.valueOf(result.get(column_name)));
						boolean warning = false;
						String warningTitle = "";
						if(value != null) {
							List<PartsWarn> partsWarns = null;
							partsWarns = partsWarnService.getAllWarnById(partsAttributes.getId());
							for(int j=0;j<partsWarns.size();j++) {
								PartsWarn partsWarn = partsWarns.get(j);
								Double minVal = partsWarn.getWarnMinValue();
								int minType = partsWarn.getWarnMinValueType();
								boolean minWarning = this.isWarning(value, minVal, minType);
								Double maxVal = partsWarn.getWarnMaxValue();
								int maxType = partsWarn.getWarnMaxValueType();
								boolean maxWarning = this.isWarning(value, maxVal, maxType);
								warningTitle = partsWarn.getWarnStatus();
								if(minWarning && maxWarning) {
									warning = true;
									break;
								}
							}
						}
						map.put("warning"+i, warning);
						map.put("warningTitle"+i, warningTitle);
					}
				}
			}
		}
	}
	
	/**
	 * 是否警告
	 * @param letfVal
	 * @param rightVal
	 * @param type
	 * @return
	 */
	private boolean isWarning(Double letfVal, Double rightVal,int type) {
		boolean isW = true;
		if(letfVal != null && rightVal != null) {
			switch (type) {
			case 1:
				isW = letfVal > rightVal;
				break;
			case 2:
				isW = letfVal >= rightVal;
				break;
			case 3:
				isW = letfVal < rightVal;
				break;
			case 4:
				isW = letfVal <= rightVal;
				break;
			}
		}
		return isW;
	}
	
	/**
	 * 获取警告类型代码所对应的警告类型
	 * @param partsType
	 * @param warnStatus
	 * @return
	 */
	private String getWarnStatus(String partsType, String warnStatus) {
		String result = "";
		WarnStatus warn = warnStatusService.getRepository().getByPartsTypeAndWarnStatus(partsType, warnStatus);
		if(warn != null) {
			result = warn.getWarnStatusName();
		}else {
			result = "未知告警";
		}
		return result;
	}
	
	/**
	 * 获取故障类型代码所对应的故障类型
	 * @param errorStatus
	 * @return
	 */
	private String getErrorStatus(String errorStatus) {
		String result = "";
		ErrorStatus error = errorStatusService.getRepository().findByErrorStatus(errorStatus);
		if(error != null) {
			result = error.getErrorStatusName();
		}else {
			result = "未知异常";
		}
		return result;
	}
}
